from flask import Blueprint
from deco import Deco
from config import Config
from time import strftime, localtime
from common import missionPanel, mConf

Mission = Blueprint("mission", __name__)

def lastMissionId():
    if len(mConf["mission"]) == 0:
        return 1
    return int(list(mConf["mission"].keys())[-1])

def searchById(k):
    if isinstance(k, int):
        k = str(k) # 因为 json 不允许把数字作为键
    if k in mConf["mission"]:
        return True, mConf["mission"][k]
    return False, None

@Mission.route("/mission/create", methods = ["POST"])
@Deco
def createMission(p): # p 代表 postdata
    mConf["mission"][str(lastMissionId() + 1)] = {
        "name": p["name"],
        "description": p["description"],
        "createTime": strftime("%Y-%m-%d %H:%M:%S", localtime()),
        "status": "Stopped"
    }
    mConf.save() # 我不知道该怎么自动了
    return True, "创建成功"

@Mission.route("/mission/list", methods = ["GET"])
@Deco
def missionList():
    tmp = mConf["mission"]
    ret = []
    for k, v in tmp.items():
        ret.append({**v, **{"id": int(k)}})
    return True, "获取成功", {"mission": ret}

@Mission.route("/mission/<int:id>/modify", methods = ["POST"])
@Deco
def modifyMission(p, id):
    id = str(id)
    if id not in mConf["mission"]:
        return False, "id 不存在"
    mConf["mission"][id]["name"] = p["name"]
    mConf["mission"][id]["description"] = p["description"]
    mConf.save()
    return True, "修改成功"

@Mission.route("/mission/<int:id>/delete", methods = ["POST"])
@Deco
def deleteMission(p, id):
    id = str(id)
    if id not in mConf["mission"]:
        return False, "id 不存在"
    mConf["mission"].pop(id)
    mConf.save()
    return True, "删除成功"

@Mission.route("/mission/<int:id>/start", methods = ["POST"])
@Deco
def startMission(p, id):
    id = str(id)
    if id not in mConf["mission"]:
        return False, "id 不存在"
    missionPanel.startMission(id)
    mConf["mission"][id]["status"] = "Running"
    mConf.save()
    return True, "操作成功"
    
@Mission.route("/mission/<int:id>/stop", methods = ["POST"])
@Deco
def stopMission(p, id):
    id = str(id)
    if id not in mConf["mission"]:
        return False, "id 不存在"
    missionPanel.stopMission(id)
    mConf["mission"][id]["status"] = "Stopped"
    mConf.save()
    return True, "操作成功"

@Mission.route("/mission/<int:id>/status", methods = ["GET"])
@Deco
def missionStatus(id):
    id = str(id)
    if id not in mConf["mission"]:
        return False, "id 不存在"
    return True, "获取成功", {**missionPanel.missionStatus(id),
                             **mConf["mission"][id]
                            }